package com.yc.base;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * <p>
 *  基础ServiceImpl
 * <p>
 *
 * @author BAO
 * @since 2020/11/16 11:28
 */
public class BaseServiceImpl <M extends CommonMapper<T>, T> extends ServiceImpl<M, T> {

    private static final int BATCH_SIZE = 1000;

    @Transactional(rollbackFor = Exception.class)
    public boolean fastSaveBatch(List<T> list, int batchSize) {
        if(CollectionUtils.isEmpty(list)) {
            return true;
        }

        if(list.size() <= batchSize) {
            return SqlHelper.retBool(baseMapper.insertBatchSomeColumn(list));
        }

        for (int fromIdx = 0 , endIdx = batchSize ; ; fromIdx += batchSize, endIdx += batchSize) {
            if(endIdx > list.size()) {
                endIdx = list.size();
            }
            baseMapper.insertBatchSomeColumn(list.subList(fromIdx, endIdx));
            if(endIdx == list.size()) {
                return true;
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean fastSaveBatch(List<T> list) {
        return fastSaveBatch(list, BATCH_SIZE);
    }

    public boolean updateAllColById(T t) {
        return retBool(baseMapper.alwaysUpdateSomeColumnById(t));
    }

    /**
     * 对某个字段过滤重复数据
     * */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }
}
